package handler

import (
	"encoding/json"
	"food-hub/cache"
	"food-hub/model"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	var foods []model.Foods
	model.DB.Select("*").Find(&foods)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": foods,
	})
}
func Detail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var foods model.Foods
	model.DB.Select("*").Where("id = ?", id).Limit(1).Find(&foods)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": foods,
	})
}
func Page(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var foods []model.Foods
	redis_key := "foods_page_" + strconv.Itoa(page)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		jsonData, _ := json.Marshal(&foods)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
		model.DB.Select("*").Offset(offset).Limit(size).Find(&foods)
	} else {
		json.Unmarshal([]byte{}, &foods)
	}

	var total int64
	model.DB.Model(&foods).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  foods,
		"total": total,
	})
}
func Add(c *gin.Context) {
	name := c.PostForm("name")
	price, _ := strconv.Atoi(c.PostForm("price"))
	num, _ := strconv.Atoi(c.PostForm("num"))
	if name == "" || price == 0 || num == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	data := model.Foods{
		Name:  name,
		Price: price,
		Num:   num,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
